const fs = require('fs');
const express = require('express');
const httpProxy = require('http-proxy');
const path = require('path');

const config = require('../webpack.config')({
  BUILD_ENV: "DEV"
});

const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

const profile = require('./settings/profile');
const apiMapping = require('./settings/api');
const mockDataRootPath = path.join(__dirname, 'mock-data');

const rootPath = path.resolve(__dirname, '../..');

const getMockDataInfo = (url) => {
  const mappingObj = apiMapping[url];
  if (mappingObj) {
    return {
      path: path.join(mockDataRootPath, mappingObj.filename + '.json'),
      status: mappingObj.status
    };
  } else {
    return {
      path: path.join(mockDataRootPath, 'empty.json'),
      status: 200
    };
  }
};

let isMock = false;

if (process.argv.length === 3 && process.argv[2] === 'mock') {
  isMock = true;
}

const app = express();

const proxy = httpProxy.createProxyServer({
  target: {
    host: profile.backend.host,
    port: profile.backend.port
  }
});

proxy.on('error', function(err, req, res) {
  res.status(500).json({
    message: err.message
  });
});

const port = profile.frontend.port;
const compiler = webpack(config);

app.use(webpackDevMiddleware(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));

app.use(webpackHotMiddleware(compiler));

app.all(profile.appCtxPath + "/**", function(req, res) {
  if (isMock) {

    const api = req.url.replace(/\?.*$/, '').replace(profile.appCtxPath, '');
    const dataInfo = getMockDataInfo(api);
    const data = fs.readFileSync(dataInfo.path);
    res.status(dataInfo.status).json(JSON.parse(data));

  } else {
    return proxy.web(req, res);
  }
});

app.use('/', function(req, res) {
  res.sendFile(rootPath + '/resources/index_dev.html');
});

app.use(express.static(rootPath + '/resources/'));

app.listen(port, function(error) {
  if (error) {
    throw error;
  } else {
    console.info("Listening on port %s.", port);
  }
});
